<?php

namespace app\admin\logic;

use think\facade\Request;
use app\admin\model\AdminModel;
use app\admin\model\SmsRecordModel;
use app\api\controller\SendMessage;
use think\Model;
use app\admin\logic\BasicLogic;
use app\admin\validate\AdminLogin;
use think\facade\Validate;
use Firebase\JWT\JWT;
use think\facade\Cache;
use app\data\cache\CacheToken;
use think\facade\Db;


class AdminLogic extends BasicLogic
{
    //注入所需模型以及操作类
    protected $adminModel     = null;
    protected $smsRecordModel = null;
    protected $adminLogin     = null;
    public function __construct(
        AdminModel     $adminModel,
        SmsRecordModel $smsRecordModel,
        AdminLogin     $adminLogin
    )
    {
        $this->adminModel     = $adminModel;
        $this->smsRecordModel = $smsRecordModel;
        $this->adminLogin     = $adminLogin;
    }

    /**
     * @desc 登录发送短信验证码
     * @author  xx
     * @date 2024-02-29
     */
    public function  sendSms($data=[]){
        $request = Request::instance();
        if ($request->isPost()){
            //获取员工的手机号;
            $docTel  = $data['tel']??'';
            $smsType = $data['smsType']??'';
            $isTel   = isMobiles($docTel);
            if($isTel == false){
                return $this->jsonMessage(201, false, '手机号格式有误', null);
            }

            if(!$smsType){
                return $this->jsonMessage(201, false, '短信类型不能为空', null);
            }

            $is_exist = self::getAccount($docTel);
            if($is_exist){
                return $this->jsonMessage(201, false, $is_exist, null);
            }
            $res = (new SendMessage())->sendCode(['tel'=>$docTel,'smsType'=>$smsType]);
            if(isset($res['res']['Code']) && isset($res['data']['code']) && $res['res']['Code']=='OK'){
                self::addSmsRecord($res['data']);
                return $this->jsonMessage(200, true, '获取成功', $res['data']['code']);
            }else{
                return $this->jsonMessage(201, false, '获取失败', null);
            }
        }

    }


    /**
     * @desc 手机号登录
     * @author xx
     * @date 2024-03-01
     */
    public function telLogin($data=[]){
        $data['smsType'] = '1';
        //验证器参数验证
        $res = $this->adminLogin->check($data);
        if(!$res) return $this->jsonMessage(201, false, $this->adminLogin->getError(), null);
        //验证码是否有效验证
        $is_right =  self::checkCode($data);
        if($is_right) return $this->jsonMessage(201, false, $is_right, null);
        //查询该手机号用户是否存在;
        $is_exist = self::getAccount($data['tel']);
        if($is_exist) return $this->jsonMessage(201, false, $is_exist, null);
        //没有问题把TOEKN传过去登录成功
        $res = self::createToken($data['tel']);
        if(!is_array($res))  return $this->jsonMessage(201, false, $res, null);
        //更新登录时间;
        $this->adminModel->where(['id'=>$res['id']])->update(['last_login_time'=>time()]);
        //更新验证码状态;
        //$this->smsRecordModel->where(['tel'=>$data['tel'],'code'=>$data['checkCode']])->update(['is_used'=>'on']);
        return $this->jsonMessage(200, true, '登录成功', $res);
    }


    /**
     * @desc 手机号登出
     * @author xx
     * @date 2024-03-05
     */
    public function loginOut(){
        return $this->jsonMessage(200, true, '登出成功', null);
    }















    /**
     * @desc 存储验证码信息
     * @author xx
     * @date 2024-02-29
     *
     */
    public function addSmsRecord($param){
        $data['tel']          = $param['tel'];
        $data['sms_type']     = $param['sms_type'];
        $data['code']         = $param['code'];
        $data['message']      = $param['message'];
        $data['created_time'] = date('Y-m-d H:i:s',time());
        $data['expire_time']  = date('Y-m-d H:i:s',strtotime('+7 days'));
        $this->smsRecordModel->insert($data);
    }


    /**
     * 检验验证码
     * @param $value
     * @param $rule
     * @param $data
     * @return bool|string
     */
    protected function checkCode($data){
        $map["sms_type"]  =   $data['smsType'];
        $map["tel"]       =   $data['tel'];
        $map["code"]      =   $data['checkCode'];
        $obj              =   $this->smsRecordModel->where($map)->order("created_time desc")->find();
        //是否使用过验证码
        if (!isset($obj['code'])) {
            return '验证码不正确';
        }else{
            if($obj['is_used'] == 'on'){
                return '验证码已经使用过了';
            }
            if($obj['expire_time'] < date('Y-m-d H:i:s',time())){
                return '验证码已过期';
            }
            return '';
        }
    }

    /**
     * @desc 查看员工是否存在
     * @author xx
     * @date 2024-03-01
     *
     */
    private function getAccount($tel=''){
        $res = $this->adminModel->where(['mobile'=>$tel])->find();
        $res = objectToArray($res);
        if($res){
            return isset($res['status']) && $res['status']==0 ? '该员工账号被禁用' : '';
        }else{
            return '该员工还未授权';
        }
    }


    /**
     * @DESC 生成登录token
     * @author  xx
     * @date 2024-03-01
     */
    private function createToken($tel){
        $info = $this->adminModel->where(['mobile'=>$tel])->find();
        $info = objectToArray($info);
        //获取当前登录员工的分组ID;
        $groupId = Db::name('admin_group_access')->where(['uid'=>$info["id"]])->value('group_id');
        if(!$groupId)  return '请给该员工配置角色分组';
        //生成token;
        $newToken = tokens();
        $token = [
            "id"               => $info["id"],
            "tel"              => $info["mobile"],
            "username"         => $info["username"],
            "nickname"         => $info["nickname"],
            "avatar"           => $info["avatar"],
            "email"            => $info["email"],
            "last_login_time"  => $info["last_login_time"],
            "groupId"          => $groupId,
            "token"            => $newToken
        ];
        $jwt = JWT::encode($token, env('JWT_JWT_SALT'));
        //缓存客户端token;
        CacheToken::setAdminPcData($tel, $newToken);
        //返回登录信息;
        return [
           'id'              =>$info['id'],
           'mobile'          =>$info['mobile'],
           'username'        =>$info['username'],
           'nickname'        =>$info['nickname'],
           'avatar'          =>$info['avatar'],
           'email'           =>$info['email'],
           'last_login_time' =>$info['last_login_time'],
           'groupId'         =>$groupId,
           'token'           =>$jwt,
        ];
    }



}